<template>
  <div>
    <Title title="人员列表"> </Title>
    <!-- 搜索功能 -->
    <el-row class="mb15">
      <el-col :span="7">
        <el-input
          v-model="obj.keyword"
          placeholder="搜索关键字(用户名或者手机号或者身份)"
        ></el-input>
      </el-col>
      <el-col :span="7" :offset="1">
        <el-select
          v-model="obj.role"
          class="m-2"
          style="width: 100%"
          placeholder="用户身份"
          size="default"
        >
          <el-option
            v-for="item in roleList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-col>
      <el-col :span="7" :offset="1">
        <el-button type="success" @click="startSearch">搜索</el-button>
        <el-button type="danger" @click="resetData">重置</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="22" v-if="userInfo">
        <el-table :data="userList" border style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="60"
          ></el-table-column>
          <el-table-column prop="title" label="用户名" align="center">
            <template #default="scope">
              <span> {{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="手机号" align="center">
            <template #default="scope">
              <span> {{ $filters.telformat(scope.row.phone) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="time" label="注册时间" align="center">
            <template #default="scope">
              <span> {{ $filters.timeFormat(scope.row.time) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="role" label="身份角色" align="center">
            <template #default="scope">
              <el-tag :color="roleList[scope.row.role - 1]?.color">
                {{ roleList[scope.row.role - 1]?.label }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <div v-if="userInfo.role > scope.row.role">
                <el-popconfirm
                  confirm-button-text="Yes"
                  cancel-button-text="No"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  @confirm="confirmDelOne(scope.row, scope.$index)"
                  title="你确定要删除吗?"
                >
                  <template #reference>
                    <el-button type="danger" size="small">删除</el-button>
                  </template>
                </el-popconfirm>

                <el-button
                  size="small"
                  @click="updateOne(scope.row, scope.$index)"
                  >修改</el-button
                >
              </div>
              <div v-else>暂无权限</div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <!-- 表单内容写在slot里面是因为每个弹出框的表单内容不一样 。再有弹出框可以再次使用-->
    <DialogForm
      title="修改用户信息"
      ref="diaform"
      :form="form"
      :rules="rules"
      :comfirmChange="comfirmChange"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          clearable
          v-model="form.username"
          placeholder="用户名"
          type="text"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          clearable
          v-model="form.phone"
          placeholder="手机号"
          type="text"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          disabled
          v-model="form.password"
          placeholder="密码"
          type="text"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="用户身份" prop="role">
        <el-select
          v-model="form.role"
          class="m-2"
          style="width: 100%"
          placeholder="用户身份"
          size="default"
        >
          <el-option
            v-for="item in roleList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="!(userInfo.role > item.value)"
          />
        </el-select>
      </el-form-item>
    </DialogForm>
  </div>
</template>

<script lang="ts" setup>
import { InfoFilled } from "@element-plus/icons-vue";
import { ref, computed, onMounted, reactive } from "vue";
import { useStore } from "@/store";
import { Ajax } from "../../api";
import DialogForm from "@/components/DialogForm.vue";
import { reg } from "../../utils/validate";
import { ShowErrorMsg } from "../../utils";
const store = useStore();
const { getUserList, changeUserList } = store;
const diaform = ref<any>();
const rules = reactive({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur",
    },
    {
      pattern: reg.phone,
      message: "请输入正确格式的手机号码",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      pattern: reg.pwd,
      message: "请输入6-16位的数字和字母组合的密码",
      trigger: "blur",
    },
  ],
  role: [
    {
      required: true,
      message: "请选择身份",
      trigger: "change",
    },
  ],
});
const obj = ref<any>({});
const form = ref<any>({
  username: "",
  password: "",
});
const startSearch = () => {
  getUserList(obj.value); //按条件查找是带参数调用查找用户列表的方法。初次渲染和重置表单是不带参数
};
const resetData = () => {
  obj.value = {};
  getUserList();
};
const roleList = computed(() => store.roleList);
const userList = computed(() => store.userList); //script里面用就要store. html里用就不用
console.log("userList", userList);

const userInfo = computed(() => store.userInfo);

// 删除 先删除后端再删除前端数据
const confirmDelOne = async (item: any, index: number) => {
  let res: any = await Ajax.userdelete({
    _id: item._id,
  });
  if (res.code == 200) {
    store.userList.splice(index, 1);
    // 通知 store
    changeUserList(store.userList);
  }
};
// 这个是调起弹框，而不是修改
const updateOne = (item: any, index: any) => {
  // 父改子
  console.log(diaform.value);
  diaform.value.dialogVisible = true; // 不需要取 value
  form.value = Object.assign({}, item); //不知道为什么需要深拷贝
  // form.value = item;
  form.value.index = index;
};
// 有个bug：用户名和手机号需要同时改
// 这个函数传递给子组件 由子组件触发
const comfirmChange = async () => {
  let res: any = await Ajax.userupdate(form.value);
  if (res.code == 200) {
    diaform.value.handleClose();
    getUserList({});
  }
  // diaform.value.formRef.validate(async (valid:boolean)=>{
  //     if(valid){
  //         let res:any = await  Ajax.userupdate(form.value)
  //         if(res.code==200){
  //             diaform.value.handleClose()
  //             // diaform.value.formRef.resetFields()
  //             // diaform.value.dialogVisible  = false;
  //             // store.userList =
  //             // store.userList.splice(form.value.index,1,Object.assign({},form.value))
  //             console.log(form.value)  //  没有改变
  //             // var list  = store.userList.map((item:any)=>{
  //             //     if(item._id==form.value._id){
  //             //         item = Object.assign({},form.value)
  //             //     }
  //             //     return item
  //             // })
  //             // changeUserList(list)
  //             getUserList({})
  //         }
  //     }else{
  //         ShowErrorMsg('校验失败')
  //     }
  // })
};
onMounted(() => {
  getUserList({});
});
</script>
